<!-- src/pages/login/login.vue -->
<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { useUserStore } from '@/store/user'
import {
  debugLog,
  endLoginSession,
  endPerformanceTimer,
  startLoginSession,
  startPerformanceTimer,
  trackLoginStep,
} from '@/utils/wechat-debug'
import {
  hideWxLoading,
  preventDuplicateLogin,
  showWxError,
  showWxLoading,
  showWxSuccess,
} from '@/utils/wechat-error-handler'

const userStore = useUserStore()

// 登录/注册模式切换
const isLogin = ref(true)

// 登录表单数据
const loginForm = ref({
  username: '',
  password: '',
})
const showLoginPassword = ref(false)

// 注册表单数据
const registerForm = ref({
  username: '',
  // phone: '', // 注释掉手机号字段
  password: '',
  confirmPassword: '',
})
const showRegisterPassword = ref(false)

// 协议勾选状态
const agreementChecked = ref(false)
const agreementShake = ref(false)

// 计算属性：是否可以注册
const canRegister = computed(() => {
  return (
    registerForm.value.username
    // && registerForm.value.phone // 注释掉手机号验证
    && registerForm.value.password
    && registerForm.value.confirmPassword
    && agreementChecked.value
  )
})

// 切换登录/注册模式
function switchAuthMode(login) {
  isLogin.value = login
}

// 处理登录
async function handleLogin() {
  if (!loginForm.value.username || !loginForm.value.password) {
    uni.showToast({
      title: '请输入用户名和密码',
      icon: 'none',
    })
    return
  }

  try {
    await userStore.login({
      username: loginForm.value.username,
      password: loginForm.value.password,
    })

    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })

    // 登录成功后跳转
    setTimeout(() => {
      if (redirectUrl.value) {
        console.log('登录成功，跳转到重定向URL:', redirectUrl.value)
        // 如果重定向URL是tabbar页面，使用switchTab
        const tabbarPages = ['/pages/index/index', '/pages/chinese-books/index', '/pages/study-checkin/index', '/pages-sub/admin/class/index', '/pages/my/index']
        if (tabbarPages.includes(redirectUrl.value)) {
          uni.switchTab({
            url: redirectUrl.value,
          })
        }
        else {
          uni.reLaunch({
            url: redirectUrl.value,
          })
        }
      }
      else {
        // 默认跳转到我的页面
        uni.switchTab({
          url: '/pages/my/index',
        })
      }
    }, 1500)
  }
  catch (error) {
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none',
    })
  }
}

// 处理注册
async function handleRegister() {
  // 检查协议是否勾选
  if (!agreementChecked.value) {
    triggerAgreementShake()
    uni.showToast({
      title: '请先同意用户协议和隐私政策',
      icon: 'none',
    })
    return
  }

  if (!canRegister.value)
    return

  // 验证用户名
  if (!registerForm.value.username || registerForm.value.username.trim() === '') {
    uni.showToast({
      title: '用户名不能为空',
      icon: 'none',
    })
    return
  }

  if (registerForm.value.username.length < 4 || registerForm.value.username.length > 20) {
    uni.showToast({
      title: '用户名长度需为4-20位',
      icon: 'none',
    })
    return
  }

  // 验证用户名格式（只能包含字母、数字和下划线）
  if (!/^\w+$/.test(registerForm.value.username)) {
    uni.showToast({
      title: '用户名只能包含字母、数字和下划线',
      icon: 'none',
    })
    return
  }

  // 注释掉手机号验证逻辑
  // if (!registerForm.value.phone || registerForm.value.phone.trim() === '') {
  //   uni.showToast({
  //     title: '手机号不能为空',
  //     icon: 'none',
  //   })
  //   return
  // }

  // if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
  //   uni.showToast({
  //     title: '请输入正确的手机号格式',
  //     icon: 'none',
  //   })
  //   return
  // }

  // 验证密码
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none',
    })
    return
  }

  if (registerForm.value.password.length < 6 || registerForm.value.password.length > 20) {
    uni.showToast({
      title: '密码长度需为6-20位',
      icon: 'none',
    })
    return
  }

  try {
    await userStore.register({
      username: registerForm.value.username,
      // phone: registerForm.value.phone, // 注释掉手机号参数
      password: registerForm.value.password,
      confirmPassword: registerForm.value.confirmPassword,
    })

    uni.showToast({
      title: '注册成功',
      icon: 'success',
    })

    // 注册成功后自动切换到登录界面
    setTimeout(() => {
      isLogin.value = true
      // 清空注册表单
      registerForm.value = {
        username: '',
        // phone: '', // 注释掉手机号字段
        password: '',
        confirmPassword: '',
      }
    }, 1500)
  }
  catch (error) {
    uni.showToast({
      title: error.message || '注册失败',
      icon: 'none',
    })
  }
}

// 微信登录
const handleWechatLogin = preventDuplicateLogin(async () => {
  // #ifdef MP-WEIXIN
  const sessionId = startLoginSession()
  startPerformanceTimer('wechat_login_total')

  try {
    debugLog('info', '开始微信登录流程')
    trackLoginStep('开始登录', true)

    showWxLoading('正在登录...')

    // 1. 获取微信登录凭证
    startPerformanceTimer('wx_login_code')
    trackLoginStep('获取微信登录凭证', true)
    debugLog('info', '开始获取微信登录凭证')

    const loginRes = await new Promise((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          debugLog('info', '微信login API调用成功', res)
          if (res.errMsg === 'login:ok') {
            debugLog('info', '获取微信code成功', { code: `${res.code?.substring(0, 10)}...` })
            resolve(res)
          }
          else {
            debugLog('error', '获取微信code失败', res)
            reject(new Error(res.errMsg || '获取微信登录凭证失败'))
          }
        },
        fail: (err) => {
          debugLog('error', '微信login API调用失败', err)
          reject(err)
        },
      })
    })

    endPerformanceTimer('wx_login_code')
    trackLoginStep('获取微信登录凭证', true, { hasCode: !!loginRes.code })
    debugLog('info', '微信登录凭证获取完成', {
      hasCode: !!loginRes.code,
      codeLength: loginRes.code?.length,
      errMsg: loginRes.errMsg,
    })

    // 2. 获取用户信息（新版本微信小程序推荐方式）
    startPerformanceTimer('wx_get_user_profile')
    trackLoginStep('获取用户信息开始', true)
    debugLog('info', '开始获取用户信息')

    // 获取真实的微信用户信息
    let userProfile
    try {
      userProfile = await getUserProfile()
      endPerformanceTimer('wx_get_user_profile')
      trackLoginStep('获取用户信息成功', true, { hasNickname: !!userProfile.nickName })
      debugLog('info', '获取微信用户信息成功', {
        nickName: userProfile.nickName,
        hasAvatar: !!userProfile.avatarUrl,
      })
    }
    catch (profileError) {
      endPerformanceTimer('wx_get_user_profile')
      trackLoginStep('获取用户信息失败', false, null, profileError)
      debugLog('error', '获取用户信息失败，使用默认信息', profileError)

      // 如果获取用户信息失败，使用默认信息
      userProfile = {
        nickName: '微信用户',
        avatarUrl: '',
        gender: 1,
        country: '中国',
        province: '',
        city: '',
        language: 'zh_CN',
      }
      debugLog('info', '使用默认用户信息', userProfile)
    }

    // 3. 调用微信登录API（带重试机制）
    startPerformanceTimer('api_wx_login')
    trackLoginStep('调用后端登录API', true)

    debugLog('info', '准备调用后端API', {
      hasCode: !!loginRes.code,
      codeLength: loginRes.code?.length,
      hasUserInfo: !!userProfile,
      userNickname: userProfile?.nickName,
    })

    const result = await userStore.wxLogin({
      code: loginRes.code,
      userInfo: userProfile,
      deviceInfo: getDeviceInfo(),
    })

    endPerformanceTimer('api_wx_login')
    trackLoginStep('调用后端登录API', true, { hasToken: !!result.token })
    debugLog('info', '后端登录API调用成功', { userId: result.userInfo?.id })

    // 4. 登录成功处理
    hideWxLoading()
    showWxSuccess('微信登录成功')

    const totalTime = endPerformanceTimer('wechat_login_total')
    trackLoginStep('登录完成', true, { totalTime })
    endLoginSession(true)

    debugLog('info', '微信登录流程完成', { totalTime, userId: result.userInfo?.id })

    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      if (redirectUrl.value) {
        console.log('微信登录成功，跳转到重定向URL:', redirectUrl.value)
        // 如果重定向URL是tabbar页面，使用switchTab
        const tabbarPages = ['/pages/index/index', '/pages/chinese-books/index', '/pages/study-checkin/index', '/pages-sub/admin/class/index', '/pages/my/index']
        if (tabbarPages.includes(redirectUrl.value)) {
          uni.switchTab({
            url: redirectUrl.value,
          })
        }
        else {
          uni.reLaunch({
            url: redirectUrl.value,
          })
        }
      }
      else {
        // 默认跳转到我的页面
        uni.switchTab({ url: '/pages/my/index' })
      }
    }, 1500)

    return result
  }
  catch (error) {
    hideWxLoading()
    endPerformanceTimer('wechat_login_total')
    trackLoginStep('登录失败', false, null, error)
    endLoginSession(false)

    debugLog('error', '微信登录失败', error)

    // 安全地获取错误信息
    const errorMessage = error?.message || error?.errMsg || String(error) || '未知错误'

    // 根据错误类型显示不同的提示
    if (errorMessage.includes('cancel') || errorMessage.includes('deny')) {
      showWxError(error, 'wx-api', 3000)
    }
    else {
      showWxError(error, 'backend-api', 3000)
    }

    throw error
  }
  // #endif

  // #ifndef MP-WEIXIN
  debugLog('warn', '尝试在非微信环境使用微信登录')
  uni.showModal({
    title: '提示',
    content: '微信登录功能仅在微信小程序中可用',
    showCancel: false,
    confirmText: '知道了',
  })
  // #endif
})

// 获取用户信息（兼容新旧版本）
function getUserProfile() {
  return new Promise((resolve, reject) => {
    debugLog('info', '开始获取用户信息', {
      hasGetUserProfile: typeof uni.getUserProfile === 'function',
      hasGetUserInfo: typeof uni.getUserInfo === 'function',
    })

    // 优先使用新版本API
    if (uni.getUserProfile) {
      debugLog('info', '使用uni.getUserProfile获取用户信息')
      uni.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          debugLog('info', 'getUserProfile成功', res.userInfo)
          resolve({
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            country: res.userInfo.country,
            province: res.userInfo.province,
            city: res.userInfo.city,
            language: res.userInfo.language,
          })
        },
        fail: (err) => {
          debugLog('error', 'getUserProfile失败', err)
          // 在开发环境中，如果用户拒绝授权，使用默认信息
          if (process.env.NODE_ENV === 'development') {
            debugLog('info', '开发环境：使用默认用户信息')
            resolve({
              nickName: '开发用户',
              avatarUrl: '',
              gender: 1,
              country: '中国',
              province: '广东',
              city: '深圳',
              language: 'zh_CN',
            })
          }
          else {
            reject(err)
          }
        },
      })
    }
    else {
      // 降级到旧版本API
      debugLog('info', '使用uni.getUserInfo获取用户信息')
      uni.getUserInfo({
        success: (res) => {
          debugLog('info', 'getUserInfo成功', res.userInfo)
          resolve({
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            country: res.userInfo.country,
            province: res.userInfo.province,
            city: res.userInfo.city,
            language: res.userInfo.language,
          })
        },
        fail: (err) => {
          debugLog('error', 'getUserInfo失败', err)
          // 在开发环境中提供默认信息
          if (process.env.NODE_ENV === 'development') {
            debugLog('info', '开发环境：使用默认用户信息')
            resolve({
              nickName: '开发用户',
              avatarUrl: '',
              gender: 1,
              country: '中国',
              province: '广东',
              city: '深圳',
              language: 'zh_CN',
            })
          }
          else {
            reject(err)
          }
        },
      })
    }
  })
}

// 获取设备信息
function getDeviceInfo() {
  try {
    const systemInfo = uni.getSystemInfoSync()
    return `${systemInfo.platform}_${systemInfo.system}_${systemInfo.model}`
  }
  catch (error) {
    console.error('获取设备信息失败:', error)
    return 'unknown_device'
  }
}

// 切换协议勾选状态
function toggleAgreement(e) {
  agreementChecked.value = e.detail.value.length > 0
}

// 触发协议shake动画
function triggerAgreementShake() {
  agreementShake.value = true
  setTimeout(() => {
    agreementShake.value = false
  }, 1000)
}

// 通用导航方法
function navigateTo(url) {
  uni.navigateTo({ url })
}

// 显示重置密码提示
function showResetPasswordTip() {
  uni.showModal({
    title: '重置密码',
    content: '如需重置密码，请联系客服或管理员协助处理。',
    showCancel: false,
    confirmText: '知道了',
  })
}

// 重定向URL
const redirectUrl = ref('')

onLoad((options) => {
  // 页面加载时检查是否有缓存用户名
  const cachedUsername = uni.getStorageSync('username')
  if (cachedUsername) {
    loginForm.value.username = cachedUsername
  }

  // 获取重定向URL
  if (options && options.redirect) {
    redirectUrl.value = decodeURIComponent(options.redirect)
    console.log('登录页面接收到重定向URL:', redirectUrl.value)
  }
})
</script>

<template>
  <view class="login-container">
    <!-- 顶部logo -->
    <!-- <view class="login-header">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="app-name">绘本阅读</text>
    </view> -->

    <!-- 登录/注册切换 -->
    <view class="auth-tabs">
      <view
        class="tab-item"
        :class="{ active: isLogin }"
        @click="switchAuthMode(true)"
      >
        登录
      </view>
      <view
        class="tab-item"
        :class="{ active: !isLogin }"
        @click="switchAuthMode(false)"
      >
        注册
      </view>
    </view>

    <!-- 登录表单 -->
    <view v-if="isLogin" class="auth-form">
      <view class="form-group">
        <uni-icons type="person" size="20" color="#999" />
        <input
          v-model="loginForm.username"
          class="form-input"
          placeholder="请输入用户名"
          placeholder-class="placeholder"
        >
      </view>

      <view class="form-group">
        <uni-icons type="locked" size="20" color="#999" />
        <input
          v-model="loginForm.password"
          class="form-input"
          placeholder="请输入密码"
          placeholder-class="placeholder"
          :password="!showLoginPassword"
        >
        <uni-icons
          :type="showLoginPassword ? 'eye-filled' : 'eye'"
          size="20"
          color="#999"
          @click="showLoginPassword = !showLoginPassword"
        />
      </view>

      <view class="form-actions">
        <text class="forgot-password" @click="showResetPasswordTip">
          忘记密码?
        </text>
      </view>

      <button class="auth-button" @click="handleLogin">
        登录
      </button>

      <view class="social-login">
        <view class="divider">
          <view class="divider-line" />
          <text class="divider-text">
            其他登录方式
          </text>
          <view class="divider-line" />
        </view>

        <view class="social-icons">
          <!-- #ifdef MP-WEIXIN -->
          <button class="wechat-login-btn social-icon" @click="handleWechatLogin">
            <uni-icons type="weixin" size="30" color="#07C160" />
            <text class="social-text">
              微信登录
            </text>
          </button>
          <!-- #endif -->

          <!-- #ifndef MP-WEIXIN -->
          <view class="social-icon disabled">
            <uni-icons type="weixin" size="30" color="#ccc" />
            <text class="social-text">
              仅支持微信小程序
            </text>
          </view>
          <!-- #endif -->
        </view>
      </view>
    </view>

    <!-- 注册表单 -->
    <view v-else class="auth-form">
      <view class="form-group">
        <uni-icons type="person" size="20" color="#999" />
        <input
          v-model="registerForm.username"
          class="form-input"
          placeholder="请输入用户名(4-20位字母数字下划线)"
          placeholder-class="placeholder"
          maxlength="20"
        >
      </view>

      <!-- 注释掉手机号输入框 -->
      <!-- <view class="form-group">
        <uni-icons type="phone" size="20" color="#999" />
        <input
          v-model="registerForm.phone"
          class="form-input"
          placeholder="请输入手机号"
          placeholder-class="placeholder"
          type="number"
          maxlength="11"
        >
      </view> -->

      <view class="form-group">
        <uni-icons type="locked" size="20" color="#999" />
        <input
          v-model="registerForm.password"
          class="form-input"
          placeholder="请输入密码(6-20位字符)"
          placeholder-class="placeholder"
          :password="!showRegisterPassword"
        >
        <uni-icons
          :type="showRegisterPassword ? 'eye-filled' : 'eye'"
          size="20"
          color="#999"
          @click="showRegisterPassword = !showRegisterPassword"
        />
      </view>

      <view class="form-group">
        <uni-icons type="locked" size="20" color="#999" />
        <input
          v-model="registerForm.confirmPassword"
          class="form-input"
          placeholder="请确认密码"
          placeholder-class="placeholder"
          :password="!showRegisterPassword"
        >
      </view>

      <view class="form-agreement" :class="{ shake: agreementShake }">
        <checkbox-group @change="toggleAgreement">
          <label class="agreement-label">
            <checkbox :checked="agreementChecked" color="#018d71" />
            <view class="agreement-text">
              <text>我已阅读并同意</text>
              <text class="agreement-link" @click.stop="navigateTo('/pages/about/protocol')">《用户协议》</text>
              <text>和</text>
              <text class="agreement-link" @click.stop="navigateTo('/pages/about/privacy')">《隐私政策》</text>
            </view>
          </label>
        </checkbox-group>
      </view>

      <button
        class="auth-button"
        :disabled="!canRegister"
        :class="{ disabled: !canRegister }"
        @click="handleRegister"
      >
        注册
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.login-container {
  padding: 40px 30px;
  min-height: 100vh;
  background-color: #fff;
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40px;

  .logo {
    width: 80px;
    height: 80px;
    margin-bottom: 15px;
  }

  .app-name {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }
}

.auth-tabs {
  display: flex;
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    font-size: 16px;
    color: #666;
    position: relative;

    &.active {
      color: #018d71;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 25%;
        width: 50%;
        height: 3px;
        background-color: #018d71;
        border-radius: 3px;
      }
    }
  }
}

.auth-form {
  .form-group {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    margin-bottom: 20px;
    border-bottom: 1px solid #eee;

    .form-input {
      flex: 1;
      margin: 0 10px;
      font-size: 16px;
      height: 24px;
    }

    .placeholder {
      color: #999;
      font-size: 16px;
    }

    &.with-code {
      padding-right: 0;

      .code-button {
        background-color: #018d71;
        color: #fff;
        border: none;
        border-radius: 20px;
        padding: 5px 12px;
        font-size: 14px;
        min-width: 100px;
        height: 36px;

        &[disabled] {
          background-color: #ccc;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 30px;

    .forgot-password {
      color: #999;
      font-size: 14px;
    }
  }

  .form-agreement {
    display: flex;
    align-items: flex-start;
    margin: 20px 0 30px;
    font-size: 12px;
    color: #999;

    &.shake {
      animation: shake 0.05s linear 4 alternate;
    }

    .agreement-label {
      display: flex;
      align-items: flex-start;
      width: 100%;
    }

    checkbox {
      margin-right: 8px;
      margin-top: 2px;
      transform: scale(0.8);
      flex-shrink: 0;
    }

    .agreement-text {
      flex: 1;
      line-height: 1.4;
    }

    .agreement-link {
      color: #018d71;
      text-decoration: underline;
      margin: 0 2px;
    }
  }

  .auth-button {
    background-color: #018d71;
    color: #fff;
    border: none;
    border-radius: 25px;
    padding: 6px;
    font-size: 16px;

    &[disabled] {
      background-color: #ccc;
      opacity: 0.7;
    }
  }
}

.social-login {
  margin-top: 40px;

  .divider {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .divider-line {
      flex: 1;
      height: 1px;
      background-color: #eee;
    }

    .divider-text {
      padding: 0 15px;
      color: #999;
      font-size: 12px;
    }
  }

  .social-icons {
    display: flex;
    justify-content: center;

    .social-icon {
      background: none;
      border: none;
      padding: 0;
      margin: 0 15px;
      line-height: 1;
    }
  }

  // 微信按钮样式
  .social-icon {
    display: flex;
    flex-direction: column;
    align-items: center;

    &.wechat-login-btn {
      background: transparent !important;
      padding: 0 !important;
      margin: 0 15px !important;
      line-height: 1 !important;

      &::after {
        border: none !important;
      }

      .uni-icons {
        background: #07c160;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white !important;
        margin-bottom: 8px;
        transition: all 0.3s ease;

        &:hover {
          background: #06ad56;
          transform: scale(1.05);
        }
      }

      .social-text {
        font-size: 12px;
        color: #666;
        margin-top: 4px;
      }
    }

    &.disabled {
      opacity: 0.5;
      cursor: not-allowed;

      .uni-icons {
        background: #ccc;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white !important;
        margin-bottom: 8px;
      }

      .social-text {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
      }
    }
  }
}

// shake动画
@keyframes shake {
  from {
    transform: translateX(-10rpx);
  }
  to {
    transform: translateX(10rpx);
  }
}
</style>
